﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Net.NetworkInformation;
namespace TableTool
{
    public partial class InternetManage : Form
    {
      
        public InternetManage()
        {
            InitializeComponent();
            this.Load += InternetManage_Load;
            this.TopMost = true;
        }

        private void InternetManage_Load(object? sender, EventArgs e)
        {
            if (!IsAdministrator())
            {
                MessageBox.Show("请用管理员启动");
            }
            // 获取所有网络接口
            foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (ni.OperationalStatus == OperationalStatus.Up)
                {
                    // 设置为无效的DNS服务器或局域网DNS
                    RegistryKey key = Registry.LocalMachine.OpenSubKey(
                        $"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\{ni.Id}",
                        true);

                    if (key != null)
                    {
                     var nv=   key.GetValue("NameServer");
                     var dv=   key.GetValue("DhcpNameServer");
                        //key.SetValue("NameServer", "192.168.1.1", RegistryValueKind.String);
                        //key.SetValue("DhcpNameServer", "192.168.1.1", RegistryValueKind.String);
                    }
                }
            }
        }
        /// <summary>
        /// 禁止所有网络适配器
        /// </summary>
        public static void DisableAllNetworkAdapters()
        {
            foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (ni.OperationalStatus == OperationalStatus.Up)
                {
                    ExecuteNetshCommand2($"interface set interface \"{ni.Name}\" disable");
                }
            }
        }
        /// <summary>
        /// 启用网络适配器
        /// </summary>
        public static void EnableAllNetworkAdapters()
        {
            foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                ExecuteNetshCommand2($"interface set interface \"{ni.Name}\" enable");
            }
        }

        private static void ExecuteNetshCommand2(string command)
        {
            Process.Start(new ProcessStartInfo
            {
                FileName = "netsh",
                Arguments = command,
                Verb = "runas", // 以管理员身份运行
                UseShellExecute = true,
                CreateNoWindow = true
            });
        }
        private static readonly string HostsPath = Path.Combine(
       Environment.GetFolderPath(Environment.SpecialFolder.System),
       "drivers/etc/hosts");

        public static void BlockAllInternet()
        {
            try
            {
                // 备份原始hosts文件
                File.Copy(HostsPath, HostsPath + ".bak", true);

                // 重定向所有请求到本地
                using (StreamWriter sw = File.AppendText(HostsPath))
                {
                    sw.WriteLine("# 开始网络限制");
                    sw.WriteLine("127.0.0.1 *");
                    sw.WriteLine("::1 *");
                    sw.WriteLine("# 结束网络限制");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }

        public static void RestoreHostsFile()
        {
            try
            {
                if (File.Exists(HostsPath + ".bak"))
                {
                    File.Copy(HostsPath + ".bak", HostsPath, true);
                    File.Delete(HostsPath + ".bak");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }

        public void SetProxy()
        {
           
            RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
            registry.SetValue("ProxyEnable", 1);
            registry.SetValue("ProxyServer", "0.0.0.0:1"); // 无效代理地址
            // 刷新系统设置
            InternetSetOption(IntPtr.Zero, 39, IntPtr.Zero, 0);
            InternetSetOption(IntPtr.Zero, 37, IntPtr.Zero, 0);
        }
        public void CloseProxy()
        {
            // 禁用代理
            RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
            registry.SetValue("ProxyEnable", 0);

            // 刷新系统设置
            InternetSetOption(IntPtr.Zero, 39, IntPtr.Zero, 0);
            InternetSetOption(IntPtr.Zero, 37, IntPtr.Zero, 0);
        }

        // 需要导入DLL
        [DllImport("wininet.dll")]
        public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
        bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        int type =1;
        void SetFirewallRule(bool block)
        {
            if (type==0)
            {
                string ruleName = "GlobalNetworkBlock";
                string action = block ? "block" : "allow";

                // 删除可能存在的旧规则
                ExecuteNetshCommand($"advfirewall firewall delete rule name=\"{ruleName}\"");

                // 创建新规则
                if (block)
                {
                    // 阻止所有出站连接
                    //ExecuteNetshCommand(
                    //    $"advfirewall firewall add rule name=\"{ruleName}\" " +
                    //    $"dir=out action=block enable=yes " +
                    //    $"profile=any protocol=any"
                    //);

                    // 阻止所有入站连接
                    ExecuteNetshCommand(
                        $"advfirewall firewall add rule name=\"{ruleName}\" " +
                        $"dir=in action=block enable=yes " +
                        $"profile=any protocol=any"
                    );
                }
            }
            if (type==1)
            {
                if (block)
                {
                    SetProxy();
                }
                else
                {
                    CloseProxy();
                }
            }
            if (type==2)
            {
                if(block)
                {
                    // 删除默认网关
                    Process.Start("route", "delete 0.0.0.0");

                    // 添加局域网路由 (根据你的网络配置调整)
                    Process.Start("route", "add 172.16.0.0 mask 255.255.0.0 0.0.0.0");
                }
                else
                {
                    Process.Start("route", "delete 172.16.0.0");
                    Process.Start("route", "add 0.0.0.0 mask 0.0.0.0 ");
                }
            }
            if (type == 3)
            {
                if (block)
                {
                    BlockAllInternet();
                }
                else
                {
                    RestoreHostsFile();
                }
            }
            if (type == 4)
            {
                if (block)
                {
                    DisableAllNetworkAdapters();
                }
                else
                {
                    EnableAllNetworkAdapters();
                }
            }
        }
        void ExecuteNetshCommand(string command)
        {
            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = "netsh",
                Arguments = command,
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true,
                UseShellExecute = true
            };

            using (Process process = new Process())
            {
                process.StartInfo = psi;
                process.Start();
                process.WaitForExit();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            SetFirewallRule(true);
            button1.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            SetFirewallRule(false);
            button2.Enabled = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            button3.Enabled = false;
            SetFirewallRule(true);
            int.TryParse(textBox1.Text.Trim(), out int time);
            if (time == 0)
            {
                time = 5;
                textBox1.Text = "5";
            }
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(time * 1000);
                SetFirewallRule(false);
                button3.Invoke(() =>
                {
                    button3.Enabled = true;
                });
            });
        }
    }
}
